// drawingarea.h
#ifndef DRAWINGAREA_H
#define DRAWINGAREA_H

#include <QWidget>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QMouseEvent>
#include <QPointF>
#include <QList>
#include "component.h"
#include "wire.h"

class DrawingArea : public QGraphicsView
{
    Q_OBJECT

public:
    DrawingArea(QWidget *parent = nullptr);
    ~DrawingArea();

    void addComponent(Component *component);
    void addComponentAtPosition(Component *component, const QPointF &pos);
    void clear();
    bool saveToFile(const QString &fileName);
    bool loadFromFile(const QString &fileName);
    bool exportToImage(const QString &fileName);
    void setCurrentComponent(Component* component);
    void dragEnterEvent(QDragEnterEvent *event) override;
    void dropEvent(QDropEvent *event) override;

signals:
    void componentPlaced();
    void componentSelected(Component *component);
    void componentRequested(const QString& name, const QPointF& position);
    void zoomIn();
    void zoomOut();
    void resetView();

protected:
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void mouseDoubleClickEvent(QMouseEvent *event) override;
    void wheelEvent(QWheelEvent *event) override;

private:
    QGraphicsScene *scene;
    Component *currentComponent;
    Wire *currentWire;
    QPointF lastPos;
    bool isDrawingWire;
    QList<Component*> components;
    QList<Wire*> wires;
    Component* m_currentComponentToPlace; // 待放置的组件
    QGraphicsItem* m_currentDraggingItem; // 当前拖拽的图元
    QPoint m_lastPanPoint;              // 视图平移记录点

    void setupScene();
    void startDrawingWire(Component *component, const QPointF &pos);
    void continueDrawingWire(const QPointF &pos);
    void finishDrawingWire(Component *component, const QPointF &pos);
};

#endif // DRAWINGAREA_H
